package kz.kstu.scantest.business.client.reader.form;

import kz.kstu.scantest.business.client.reader.DataListener;

import java.io.ByteArrayOutputStream;


/**
 * @author Filipp_Stankevich
 *         created: 16.09.11 23:07
 */
public abstract class AbstractFormDataListener implements DataListener {

    public static final int ERROR_BYTE_POSITION = 6;

    private ByteArrayOutputStream cache = new ByteArrayOutputStream();
    private boolean isErrorData;

    @Override
    public void handleData(byte[] data) {
        for (byte b : data) {
            if (b != 13) {
                switch (b) {
                    case 7:
                        isErrorData = true;
                        cache.reset();
                        hasError();
                        break;
                    case 33:
                        handleEndButton();
                        break;
                    default:
                        cache.write(b);
                        break;
                }
            } else {
                if (cache.size() > 0) {
                    byte[] dataToHandel = cache.toByteArray();
                    if (!isErrorData) {
                        handelFormData(dataToHandel);
                    } else {
                        isErrorData = false;
                        int errorCode = FormReader.UNKNOWN_ERROR_CODE;
                        if (dataToHandel.length > ERROR_BYTE_POSITION) {
                            errorCode = dataToHandel[ERROR_BYTE_POSITION];
                        }
                        handleError(errorCode);
                    }
                    cache.reset();
                }
            }
        }
    }

    public abstract void handelFormData(byte[] data);

    public void reset() {
        isErrorData = false;
        cache.reset();
    }

    public abstract void handleEndButton();

    public abstract void handleError(int errorCode);

    public abstract void hasError();
}